﻿using System.ComponentModel;
using System.Windows;
using System.Windows.Interactivity;
using nRoute.Controls;
using nRoute.Navigation;
using nRoute.Samples.Netflix.ViewModels;

namespace nRoute.Samples.Netflix.Behaviors
{
    public class ClearSearchContainerAction
        : TargetedTriggerAction<NavigationContainer>
    {
        private ISupportSearching _searchSupporter; 

#region Overrides

        protected override void OnTargetChanged(NavigationContainer oldTarget, NavigationContainer newTarget)
        {
            if (oldTarget != null) oldTarget.Navigated -= NavigationContainer_Navigated;
            if (_searchSupporter != null) _searchSupporter.PropertyChanged -= SearchSupporter_PropertyChanged;
            _searchSupporter = null;

            if (newTarget != null) newTarget.Navigated += NavigationContainer_Navigated;
            ResolveSupporter();
            if (_searchSupporter != null) _searchSupporter.PropertyChanged += SearchSupporter_PropertyChanged;
        }

        protected override void Invoke(object parameter)
        {
            if (_searchSupporter != null) _searchSupporter.CancelSearch();
        }

#endregion

#region Handlers

        private void NavigationContainer_Navigated(object sender, Navigation.Containers.NavigatedEventArgs e)
        {
            if (_searchSupporter != null) _searchSupporter.PropertyChanged -= SearchSupporter_PropertyChanged;
            ResolveSupporter();
            if (_searchSupporter != null) _searchSupporter.PropertyChanged += SearchSupporter_PropertyChanged;
        }

        private void SearchSupporter_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "IsSearching") ResolveSupporter();
        }

        private void ResolveSupporter()
        {
            _searchSupporter = this.Target != null ? NavigationService.GetSupporter<ISupportSearching>(this.Target) : null;
            ((UIElement)this.AssociatedObject).Visibility = (_searchSupporter != null && _searchSupporter.IsSearching)
                ? Visibility.Visible : Visibility.Collapsed;
        }

#endregion

    }
}